package cash.z.ecc.android.di.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import javax.inject.Inject
import javax.inject.Provider

class ViewModelFactory @Inject constructor(
    private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>
) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        val creator = creators[modelClass] ?: creators.entries.firstOrNull {
            modelClass.isAssignableFrom(it.key)
        }?.value ?: throw IllegalArgumentException(
            "No map entry found for ${modelClass.canonicalName}. Verify that this ViewModel has" +
                    " been added to the ViewModelModule. ${creators.keys}"
        )
        @Suppress("UNCHECKED_CAST")
        return creator.get() as T
    }
}